package com.yummy.controller;

import com.yummy.common.BaseResponse;
import com.yummy.common.TokenUtils;
import com.yummy.dto.DishDto;
import com.yummy.entity.ShoppingCart;
import com.yummy.entity.User;
import com.yummy.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 添加购物车
     * @param dish
     * @return
     */
    @PostMapping("/add")

    public BaseResponse add(@RequestBody DishDto dish, HttpServletRequest request) {
        User currentUser = tokenUtils.getCurrentUser(request);
        Integer userId = currentUser.getId();
        //类型转换
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setName(dish.getName());
        shoppingCart.setStoreId(dish.getStoreId());
        shoppingCart.setImage(dish.getImage());
        shoppingCart.setUserId(Long.valueOf(userId));
        shoppingCart.setDishId(dish.getId());
        shoppingCart.setAmount(dish.getPrice());
        shoppingCart.setDishFlavor(null);

        boolean result;
        //查询当前菜品或者套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart cart = shoppingCartService.getCartsByUserAndDish(userId, dish.getId());
        if (cart!=null){
            System.out.println("已经存在："+dish.getId());
            cart.setNumber(cart.getNumber()+1);
            System.out.println("cart1"+cart);
            result = shoppingCartService.updateCart(cart);
        }else {
            System.out.println("不存在："+cart);
            shoppingCart.setNumber(1);
            result  = shoppingCartService.addCart(shoppingCart);
        }
        System.out.println("cart:" + shoppingCart);
        //设置用户id，指定当前是哪个用户的购物车数据

        shoppingCart.setUserId(Long.valueOf(userId));
        Long dishId = shoppingCart.getDishId();
        if (result){
            return BaseResponse.success().message("添加成功");
        }else {
            return BaseResponse.success().message("添加失败");
        }
    }


//        if(cartServiceOne != null){
//            //如果已经存在，就在原来数量基础上加一
//            Integer number = cartServiceOne.getNumber();
//            cartServiceOne.setNumber(number + 1);
//            shoppingCartService.updateById(cartServiceOne);
//        }else{
//            //如果不存在，则添加到购物车，数量默认就是一
//            shoppingCart.setNumber(1);
//            shoppingCart.setCreateTime(LocalDateTime.now());
//            shoppingCartService.save(shoppingCart);
//            cartServiceOne = shoppingCart;
//        }
//
//        return R.success(cartServiceOne);
//    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/queryAll/{storeId}")
    public BaseResponse queryAll(@PathVariable("storeId")int storeId,HttpServletRequest request){
        User currentUser = tokenUtils.getCurrentUser(request);
        Integer userId = currentUser.getId();
        List<ShoppingCart> carts = shoppingCartService.queryAllByUserAndStore(userId,storeId);
        return BaseResponse.success().data("carts",carts);
    }

    /**
     * 更新购物车
     * @return
     */
    @PostMapping("/update")
    public BaseResponse queryAll(@RequestBody ShoppingCart  cart){

        if (cart.getNumber()>0){
            boolean updateRs = shoppingCartService.updateCart(cart);
        }else {
            boolean removeRs =  shoppingCartService.remove(cart);
        }
        List<ShoppingCart> carts = shoppingCartService.queryAllByUserAndStore(cart.getUserId().intValue(),cart.getStoreId());
        return BaseResponse.success().data("carts",carts);
    }
//
//    /**
//     * 清空购物车
//     * @return
//     */
//    @DeleteMapping("/clean")
//    public R<String> clean(){
//        //SQL:delete from shopping_cart where user_id = ?
//
//        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
//
//        shoppingCartService.remove(queryWrapper);
//
//        return R.success("清空购物车成功");
//    }
}